import { memo, useEffect, useState } from 'react';
import { Input, Button, AutoComplete } from 'antd';
import type { AutoCompleteProps } from 'antd';
import useWindowWidth from '@/hooks/event/use-window-width';
import { SvgIcon } from '@/components/icon';
const { TextArea } = Input;
import { useChatPage, useConfigActions, useInitializeData } from '@/store/configStore';
import { useRouter } from '@/router/hooks';
import { useNavigate } from 'react-router-dom';

import { CloseOutlined } from '@ant-design/icons';
import '../style/homepage.css';

import { useIsDeepMode, useChatActions } from '@/store/chatStore';
import { LicenseEditionEnum } from '@/common';

const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
const licenseFlag = LICENSEFLAG === 'true' ? true : false;
import LicenseModal from '@/pages/components/modal/LicenseConfirm';
import { useOrchestrationStore } from '@/store/orchestrationStore';

// 定义引导问题类型
interface GuideQuestion {
  value: string;
}

interface Props {
  handleSend: (message: string) => void;
  handleInterrupt: () => void;
  changeInputType: () => void;
  isMessageSend: boolean;
  isHome: boolean;
  voice?: boolean;
}

const MessageSendInput = ({
  handleSend,
  handleInterrupt,
  changeInputType,
  isMessageSend,
  isHome,
  voice,
}: Props) => {
  const navigate = useNavigate();

  const {
    deepThinking,
    inputGuides,
    voiceEnabled
  } = useOrchestrationStore();

  useEffect(() => {
    console.log('voiceEnabled', voiceEnabled);
    // if (!voiceEnabled && voice) {
    //   changeInputType();
    // }
  }, [voiceEnabled]);

  const { isPc } = useWindowWidth();
  const [inputValue, setInputValue] = useState('');

  // const [isDeepMode, setIsDeepMode] = useState(false);
  const isDeepMode = useIsDeepMode();
  const { setIsDeepMode } = useChatActions();

  const chatPage = useChatPage();
  const router = useRouter();

  const initializeData = useInitializeData()
  const isVoiceAvaiable = initializeData?.license_edition != LicenseEditionEnum?.basic && voiceEnabled
  const isDisabled = inputValue.trim().length === 0 && !isMessageSend && !isVoiceAvaiable;

  const [options, setOptions] = useState<AutoCompleteProps['options']>([]);
  const onSelect = (value: string, option: any) => {
    console.log('onSelect', value, option);
    setInputValue(value);
  };

  // 默认引导问题列表
  const [defaultGuideQuestions, setDefaultGuideQuestions] = useState<GuideQuestion[]>([
    // { value: '校园卡丢失了怎么办？' },
    // { value: '如何申请奖学金？' },
    // { value: '学校的图书馆开放时间？' },
    // { value: '新生入学需要准备哪些材料？' },
    // { value: '学校有哪些社团组织？' },
    // { value: '如何预约实验室？' },
    // { value: '校内就餐的选择有哪些？' },
    // { value: '如何查询考试成绩？' }
  ]);

  // 合并引导问题列表
  const [guideQuestions, setGuideQuestions] = useState<GuideQuestion[]>([]);

  useEffect(() => {
    // 合并来自orchestrationStore的inputGuides和默认引导问题
    if (inputGuides && inputGuides.length > 0) {
      const mappedInputGuides = inputGuides.map(guide => ({
        value: guide.content
      }));
      setGuideQuestions([...mappedInputGuides, ...defaultGuideQuestions]);
    } else {
      setGuideQuestions([...defaultGuideQuestions]);
    }
  }, [inputGuides]);

  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);

  const handleActivateClick = () => {
    setIsLicenseModalOpen(true);
  };

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };

  const { fetchInitialInfo } = useConfigActions();
  useEffect(() => {
    const init = async () => {
      fetchInitialInfo();
    };
    init();
  }, []);

  // 处理输入变化，匹配引导问题
  const handleSearch = (value: string) => {
    if (value && value.trim() !== '') {
      // 匹配输入内容与引导问题
      const matchedQuestions = guideQuestions
        .filter(question =>
          question.value.toLowerCase().includes(value.toLowerCase()))
        .map((question, index) => ({
          value: question.value,
          label: (
            <div style={{ padding: '8px 12px' }}>
              {question.value}
            </div>
          )
        }));

      // 限制显示数量，避免太多选项
      setOptions(matchedQuestions.slice(0, 5));
    } else {
      setOptions([]);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e?.key === 'Enter' && e?.keyCode === 13 && !e?.shiftKey) {
      e.preventDefault();
      if (!inputValue) {
        return;
      }

      if (licenseFlag && !initializeData?.is_license_valid) {
        handleActivateClick();
        return;
      }
      if (isHome) {
        router.pushQuery(chatPage, {
          msg: inputValue,
        });
      } else {
        handleSend(inputValue);
        setInputValue('');
      }
    }
  };

  const handleBtnClicked = () => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    if (isHome) {
      if (inputValue.trim().length == 0) {
        isVoiceAvaiable && changeInputType();
      } else {
        router.pushQuery(chatPage, {
          msg: inputValue,
        });
      }
    } else {
      if (isMessageSend) {
        handleInterrupt();
      } else {
        if (inputValue.trim().length == 0) {
          isVoiceAvaiable && changeInputType();
        } else {
          handleSend(inputValue);
          setInputValue('');
        }
      }
    }
  };

  const textareaStyle = {
    borderRadius: '6px',
    resize: 'none' as const,
    overflowY: 'scroll' as const,
    width: '100%',
    outline: 'none',
    boxShadow: 'none',
    backgroundColor: '#fff',
    scrollbarWidth: 'none' as const,
    flexGrow: 1,
    borderWidth: 0,
    lineHeight: '30px',
  };

  const dropdownRender = (menu: React.ReactNode) => (
    <div style={{ position: 'relative' }}>
      {menu}
    </div>
  );

  return (
    <div
      className="arae-outlined"
      style={{
        display: isPc ? 'flex' : 'block',
        width: '100%',
        flexDirection: 'column',
        backgroundColor: '#fff',
        borderRadius: '16px',
        padding: '5px',
        position: 'relative',
      }}
    >
      <div style={{ display: 'flex', width: '100%' }}>
        <AutoComplete
          className="ant-select"
          options={options}
          maxLength={2000}
          onSelect={onSelect}
          onSearch={handleSearch}
          getPopupContainer={(triggerNode) => triggerNode.parentElement}
          defaultActiveFirstOption={true}
          dropdownStyle={
            isHome
              ? {
                position: 'absolute',
                top: '100%',
                left: 0,
                marginTop: 50,
                zIndex: 2000,
                borderRadius: '12px',
                width: '100%',
              }
              : {
                position: 'absolute',
                bottom: 'calc(100% + 10px)',
                left: 0,
                zIndex: 2000,
                borderRadius: '12px',
                width: '100%',
              }
          }
          dropdownRender={dropdownRender}
          value={inputValue}
          style={{
            width: '100%',
            flex: '1 1 auto',
            height: '100%',
          }}
        >
          <TextArea
            id="question"
            className="focu border:none "
            autoSize={{ minRows: 2, maxRows: 8 }}
            onChange={(e) => {
              setInputValue(e.target.value);
              handleSearch(e.target.value);
            }}
            value={inputValue}
            onKeyDown={handleKeyDown}
            placeholder={
              isPc
                ? '输入问题，发送【Enter】/ 换行【Shift+Enter】'
                : '输入问题'
            }
            style={textareaStyle}
          />
        </AutoComplete>
      </div>

      <div className="flex justify-between">
        <div className="flex items-center justify-center">
          {deepThinking && <Button
            style={{
              borderColor: isDeepMode ? '#6640FF' : '#E0E0E0',
              color: isDeepMode ? '#6640FF' : '#4C4C4C',
              backgroundColor: isDeepMode ? '#DBE9FE' : '#fff',
              margin: '2px',
            }}
            onClick={() => {
              setIsDeepMode(!isDeepMode);
            }}
          >
            <SvgIcon icon="deep-mode" size={20} color={isDeepMode ? '#6640FF' : '#4C4C4C'} />
            深度思考
          </Button>}
        </div>

        {isHome ? (
          <Button
            className="flex"
            id="submit"
            type="text"
            size="small"
            icon={
              isMessageSend ? (
                <SvgIcon icon="ic_stop" size={25} />
              ) : inputValue.trim().length == 0 ? (
                !isVoiceAvaiable
                  ?
                  <SvgIcon icon="ic_rj_send" size={25} />
                  :
                  voice ? (
                    <SvgIcon icon="ic_rj_keyboard" size={25} />
                  ) : (
                    <SvgIcon icon="ic_rj_sound" size={25} />
                  )
              ) : (
                <SvgIcon icon="ic_rj_send" size={25} />
              )
            }
            onClick={handleBtnClicked}
            style={{
              color: '#fff',
              borderRadius: '16px',
              width: isPc ? '60px' : '50px',
              height: '30px',
              backgroundColor: isDisabled ? '#CCCCCC' : '#6640ff',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              alignSelf: 'flex-end',
              justifySelf: 'end',
              margin: '5px 0px',
            }}
            disabled={isDisabled}
          />
        ) : (
          <Button
            className="flex"
            id="submit"
            type="text"
            size="small"
            icon={
              isMessageSend ? (
                <SvgIcon icon="ic_stop" size={25} />
              ) : inputValue.trim().length == 0 ? (
                !isVoiceAvaiable
                  ?
                  <SvgIcon icon="ic_rj_send" size={25} />
                  :
                  voice ? (
                    <SvgIcon icon="ic_rj_keyboard" size={25} />
                  ) : (
                    <SvgIcon icon="ic_rj_sound" size={25} />
                  )
              ) : (
                <SvgIcon icon="ic_rj_send" size={25} />
              )
            }
            onClick={handleBtnClicked}
            style={{
              color: '#fff',
              borderRadius: '16px',
              width: isPc ? '60px' : '50px',
              height: '30px',
              backgroundColor: isDisabled ? '#CCCCCC' : '#6640ff',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              alignSelf: 'flex-end',
              justifySelf: 'end',
              margin: '5px 0px',
            }}
            disabled={isDisabled}
          />
        )}
      </div>
      <LicenseModal visible={isLicenseModalOpen} onCancel={handleLicenseCancel} />
    </div>
  );
};

export default memo(MessageSendInput);
